package com.xdy.music.util;

import com.xdy.music.bean.LastPlayInfo;
import com.xdy.music.bean.SoundBean;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.dom4j.tree.DefaultAttribute;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 操作XML工具类
 */
public class XMLUtils {
    /**
     * 读取已建歌单
     * @return
     */
    public static List<String> readAllGroup(){
        List<String> groupList = new ArrayList<>();
        //创建一个SAXReader对象
        SAXReader reader = new SAXReader();
        //读取Document对象
        try {
            Document document = reader.read(XMLUtils.class.getClassLoader().getResourceAsStream("musicGroup.xml"));
            //读取根元素
            Element rootElement = document.getRootElement();
            if (rootElement == null){
                return groupList;//没有跟元素直接返回空集合
            }
            //读取根元素下的group元素
            List<Element> groupEleList = rootElement.elements();
            if (groupEleList == null || groupEleList.size() == 0){
                return groupList;//group为空直接返回空集合
            }
            for (Element element : groupEleList) {
                groupList.add(element.attributeValue("name"));
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return groupList;
    }

    /**
     * 添加歌单到xml
     * @param groupName
     */
    public static void addGroup(String groupName){
        SAXReader reader = new SAXReader();
        try {
            Document document = reader.read(XMLUtils.class.getClassLoader().getResourceAsStream("musicGroup.xml"));
            //获取根元素
            Element rootElement = document.getRootElement();
            //添加group元素，并且返回该元素
            Element groupElement = rootElement.addElement("group");
            groupElement.addAttribute("name",groupName);
            groupElement.addAttribute("createDate",new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));
            OutputFormat outputFormat = OutputFormat.createPrettyPrint();
            outputFormat.setEncoding("UTF-8");
            outputFormat.setExpandEmptyElements(true);//生成完整标签<group></group>,而不是<group/>
            //创建XML文件输出流
            XMLWriter xmlWriter = new XMLWriter(new FileWriter("out/production/music_box/musicGroup.xml"),outputFormat);
            //把新的文档重新写入到XML文件中
            xmlWriter.write(document);
            //释放资源
            xmlWriter.close();
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除XML中已添加的歌单
     * @param groupName
     */
    public static void deleteGroup(String groupName){
        SAXReader reader = new SAXReader();
        try {
            Document document = reader.read(XMLUtils.class.getClassLoader().getResourceAsStream("musicGroup.xml"));
            Element rootElement = document.getRootElement();
            if (rootElement == null){
                return;
            }
            List<Element> elements = rootElement.elements();
            if (elements == null || elements.size() == 0){
                return;
            }
            //遍历所有元素，寻找要删除的歌单元素
            for (Element element : elements) {
                if (groupName.equals(element.attributeValue("name"))){
                    rootElement.remove(element);
                    break;
                }
            }
            OutputFormat outputFormat = OutputFormat.createPrettyPrint();
            outputFormat.setEncoding("UTF-8");
            outputFormat.setExpandEmptyElements(true);//完整标签
            //从新写入文档
            XMLWriter writer = new XMLWriter(new FileWriter("out/production/music_box/musicGroup.xml"),outputFormat);
            writer.write(document);
            writer.close();
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 读取上次关闭时保存的歌曲和歌单信息
     * @return
     */
    public static String[] readPrePlayInfo(){
        SAXReader reader = new SAXReader();
        Document document = null;
        try {
            document = reader.read(XMLUtils.class.getClassLoader().getResourceAsStream("playInfo.xml"));
            Element rootElement = document.getRootElement();
            if (rootElement == null){
                return null;
            }
            Element currentGroup = rootElement.element("currentGroup");
            if (currentGroup == null){
                return null;
            }
            String groupName = currentGroup.attributeValue("name");
            Element currentIndex = currentGroup.element("currentIndex");
            if (currentIndex == null){
                return null;
            }
            String index = currentIndex.getText();
            String[] playInfo = new String[2];
            playInfo[0] = groupName;
            playInfo[1] = index;
            return playInfo;
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取该歌单下的所有歌曲信息
     * @param groupName
     * @return
     */
    public static List<SoundBean> getAllSoundWithGroupName(String groupName){
        SAXReader reader = new SAXReader();
        List<SoundBean> soundBeanList = new ArrayList<>();
        try {
            Document document = reader.read(XMLUtils.class.getClassLoader().getResourceAsStream("musicGroup.xml"));
            Element rootElement = document.getRootElement();
            if (rootElement == null){
                return soundBeanList;
            }
            List<Element> groupList = rootElement.elements();
            if (groupList == null || groupList.size() == 0){
                return soundBeanList;
            }
            for (Element group : groupList) {
                if(group.attributeValue("name").equals(groupName)){
                    List<Element> soundList = group.elements();
                    for (Element sound : soundList) {
                        SoundBean soundBean = new SoundBean();
                        soundBean.setFilePath(sound.elementText("filePath"));
                        soundBean.setAddDate(sound.elementText("addDate"));
                        soundBeanList.add(soundBean);
                    }
                }
            }
            return soundBeanList;
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return soundBeanList;
    }

    /**
     *
     * @param groupName
     * @param soundPath
     */
    public static void deleteSoundWithGroup(String groupName,String soundPath){
        SAXReader reader = new SAXReader();
        try {
            Document document = reader.read(XMLUtils.class.getClassLoader().getResourceAsStream("musicGroup.xml"));
            Element rootElement = document.getRootElement();
            if (rootElement == null){
                return;
            }
            List<Element> elements = rootElement.elements();
            if (elements == null || elements.size() == 0){
                return;
            }
            for (Element group : elements) {
                if (group.attributeValue("name").equals(groupName)){
                    List<Element> soundList = group.elements();
                    if (soundList == null || soundList.size() == 0){
                        return;
                    }
                    for (Element sound : soundList) {
                        if (sound.elementText("filePath").equals(soundPath)){
                            group.remove(sound);//删除该歌曲元素
                        }
                    }
                }
            }
            OutputFormat outputFormat = OutputFormat.createPrettyPrint();
            outputFormat.setExpandEmptyElements(true);//生成完整标签
            outputFormat.setEncoding("UTF-8");
            XMLWriter writer = new XMLWriter(new FileWriter("out/production/music_box/musicGroup.xml"),outputFormat);
            writer.write(document);
            writer.close();
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     *
     * @param groupName
     * @param soundPath
     */
    public static void addSoundWithGroup(String groupName,String soundPath){
        SAXReader reader = new SAXReader();
        try {
            Document document = reader.read(XMLUtils.class.getClassLoader().getResourceAsStream("musicGroup.xml"));
            Element rootElement = document.getRootElement();
            if (rootElement == null){
                return;
            }
            List<Element> elements = rootElement.elements();
            if (elements == null || elements.size() == 0){
                return;
            }
            for (Element group : elements) {
                if (group.attributeValue("name").equals(groupName)){
                    //添加音乐
                    Element sound = group.addElement("sound");
                    Element filePath = sound.addElement("filePath");
                    filePath.addText(soundPath);
                    Element addDate = sound.addElement("addDate");
                    addDate.addText(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));
                }
            }
            OutputFormat outputFormat = OutputFormat.createPrettyPrint();
            outputFormat.setExpandEmptyElements(true);//生成完整标签
            outputFormat.setEncoding("UTF-8");
            XMLWriter writer = new XMLWriter(new FileWriter("out/production/music_box/musicGroup.xml"),outputFormat);
            writer.write(document);
            writer.close();
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 关闭时保存当前的播放歌单和歌曲索引
     * @param groupName
     * @param index
     */
    public static void saveLastPlayInfo(String groupName,int index){
        SAXReader reader = new SAXReader();
        try {
            Document document = reader.read(XMLUtils.class.getClassLoader().getResourceAsStream("playInfo.xml"));
            Element rootElement = document.getRootElement();
            if (rootElement == null){
                return;
            }
            Element currentGroup = rootElement.element("currentGroup");
            if (currentGroup != null){
                List<Attribute> list = new ArrayList<>();
                list.add(new DefaultAttribute("name",groupName));
                currentGroup.setAttributes(list);
                Element currentIndex = currentGroup.element("currentIndex");
                if (currentIndex != null){
                    currentIndex.setText(String.valueOf(index));
                }else{
                    currentGroup.addElement("currentIndex").setText(String.valueOf(index));
                }
            }else{
                Element currentGroup1 = rootElement.addElement("currentGroup");
                currentGroup1.addAttribute("name",groupName);
                Element currentIndex = currentGroup1.addElement("currentIndex");
                currentIndex.setText(String.valueOf(index));
            }
            OutputFormat outputFormat = OutputFormat.createPrettyPrint();
            outputFormat.setEncoding("UTF-8");
            outputFormat.setExpandEmptyElements(true);
            XMLWriter writer = new XMLWriter(new FileWriter("out/production/music_box/playInfo.xml"),outputFormat);
            writer.write(document);
            writer.close();
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取关闭前播放的歌单和歌曲索引
     * @return
     */
    public static LastPlayInfo getPrePlayInfo(){
        try {
            SAXReader reader = new SAXReader();
            Document document = reader.read(XMLUtils.class.getClassLoader().getResourceAsStream("playInfo.xml"));
            Element rootElement = document.getRootElement();
            if (rootElement == null){
                return null;
            }
            Element currentGroup = rootElement.element("currentGroup");
            if (currentGroup == null){
                return null;
            }
            LastPlayInfo playInfo = new LastPlayInfo();
            playInfo.setGroupName(currentGroup.attributeValue("name"));
            Element currentIndex = currentGroup.element("currentIndex");
            if (currentIndex == null){
                return playInfo;
            }
            playInfo.setIndex(Integer.parseInt(currentIndex.getText()));
            return playInfo;
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return null;
    }
}
